<template>
  <div class="food-detail-page">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-6">
        <div class="flex flex-col space-y-4">
          <!-- 面包屑导航 -->
          <el-breadcrumb separator="/" class="text-sm">
            <el-breadcrumb-item :to="{ path: '/food' }"
              >特色美食</el-breadcrumb-item
            >
            <el-breadcrumb-item>{{ foodDetail.name }}</el-breadcrumb-item>
          </el-breadcrumb>

          <!-- 标题和操作按钮 -->
          <div class="flex items-center justify-between">
            <h1
              class="text-2xl font-bold text-gray-900 dark:text-white line-clamp-1 flex-1 mr-4"
            >
              {{ foodDetail.name }}
            </h1>
            <div class="flex items-center gap-3">
              <el-button-group>
                <el-button
                  type="primary"
                  plain
                  :icon="Share"
                  @click="handleShare"
                >
                  分享
                </el-button>
                <el-button
                  :type="foodDetail.isFavorited ? 'primary' : 'default'"
                  plain
                  :icon="Star"
                  @click="handleFavorite"
                >
                  {{ foodDetail.isFavorited ? "已收藏" : "收藏" }}
                </el-button>
              </el-button-group>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧主要内容区 -->
        <div class="flex-1">
          <!-- 美食内容 -->
          <div
            class="food-content bg-white dark:bg-gray-800 rounded-lg shadow-sm"
            v-loading="loading"
          >
            <!-- 美食元信息 -->
            <div class="border-b border-gray-100 dark:border-gray-700 p-6">
              <div
                class="flex items-center gap-6 text-sm text-gray-500 dark:text-gray-400"
              >
                <div class="category">
                  <el-tag size="small" effect="light">
                    {{ foodDetail.category }}
                  </el-tag>
                </div>
                <div class="location flex items-center">
                  <el-icon class="mr-1"><Location /></el-icon>
                  <span>{{ foodDetail.location }}</span>
                </div>
                <div class="views flex items-center">
                  <el-icon class="mr-1"><View /></el-icon>
                  <span>{{ formatNumber(foodDetail.views, 'views') }}次浏览</span>
                </div>
              </div>
            </div>

            <!-- 美食图片展示 -->
            <div class="p-6">
              <el-carousel :interval="4000" type="card" height="400px">
                <el-carousel-item
                  v-for="image in foodDetail.images"
                  :key="image"
                >
                  <el-image
                    :src="image"
                    fit="cover"
                    class="w-full h-full rounded-lg"
                    :preview-src-list="foodDetail.images"
                  />
                </el-carousel-item>
              </el-carousel>
            </div>

            <!-- 美食介绍 -->
            <div
              class="food-description prose dark:prose-invert max-w-none p-6"
            >
              <!-- 概述 -->
              <div class="mb-8">
                <h2 class="text-xl font-bold mb-4">美食介绍</h2>
                <div class="bg-gray-50 dark:bg-gray-700 rounded-lg p-6">
                  <p
                    class="text-gray-600 dark:text-gray-400 leading-relaxed mb-6"
                  >
                    艇仔粥是贵港最具特色的传统美食之一，以其独特的烹饪方法和鲜美的口感而闻名。
                  </p>

                  <div>
                    <h4 class="font-medium text-gray-900 dark:text-white mb-3">
                      特色介绍
                    </h4>
                    <p class="text-gray-600 dark:text-gray-400 leading-relaxed">
                      艇仔粥选用上等大米，配以新鲜的河鲜食材，经过长时间熬制而成。粥质细腻，鲜味十足，是一道老少皆宜的美食。
                    </p>
                  </div>
                </div>
              </div>

              <!-- 特色口味 -->
              <div class="mb-8">
                <h2 class="text-xl font-bold mb-4">特色口味</h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div
                    v-for="(taste, index) in foodDetail.tastes"
                    :key="index"
                    class="flex items-start gap-3 bg-gray-50 dark:bg-gray-700 rounded-lg p-4"
                  >
                    <el-icon class="text-primary-600 text-xl mt-1"
                      ><Food
                    /></el-icon>
                    <div>
                      <h4
                        class="font-medium text-gray-900 dark:text-white mb-1"
                      >
                        {{ taste.name }}
                      </h4>
                      <p class="text-sm text-gray-600 dark:text-gray-400">
                        {{ taste.description }}
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 制作工艺 -->
              <div class="mb-8">
                <h2 class="text-xl font-bold mb-4">制作工艺</h2>
                <div class="space-y-4">
                  <div
                    v-for="(step, index) in foodDetail.cookingSteps"
                    :key="index"
                    class="flex gap-4 bg-gray-50 dark:bg-gray-700 rounded-lg p-4"
                  >
                    <div
                      class="flex-shrink-0 w-8 h-8 bg-primary-600 text-white rounded-full flex items-center justify-center font-medium"
                    >
                      {{ index + 1 }}
                    </div>
                    <div class="flex-1">
                      <h4
                        class="font-medium text-gray-900 dark:text-white mb-2"
                      >
                        {{ step.title }}
                      </h4>
                      <p class="text-gray-600 dark:text-gray-400">
                        {{ step.description }}
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 营养价值 -->
              <div class="mb-8">
                <h2 class="text-xl font-bold mb-4">营养价值</h2>
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div
                    v-for="(nutrition, index) in foodDetail.nutritions"
                    :key="index"
                    class="bg-gray-50 dark:bg-gray-700 rounded-lg p-4 text-center"
                  >
                    <div class="text-2xl font-bold text-primary-600 mb-1">
                      {{ nutrition.value }}
                    </div>
                    <div class="text-sm text-gray-600 dark:text-gray-400">
                      {{ nutrition.name }}
                    </div>
                  </div>
                </div>
              </div>

              <!-- 食用建议 -->
              <div class="mb-8">
                <h2 class="text-xl font-bold mb-4">食用建议</h2>
                <div class="bg-gray-50 dark:bg-gray-700 rounded-lg p-6">
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                      <h4
                        class="font-medium text-gray-900 dark:text-white mb-3"
                      >
                        最佳食用时节
                      </h4>
                      <div class="flex flex-wrap gap-2">
                        <el-tag
                          v-for="season in foodDetail.bestSeasons"
                          :key="season"
                          effect="light"
                          class="mr-2"
                          >{{ season }}</el-tag
                        >
                      </div>
                    </div>
                    <div>
                      <h4
                        class="font-medium text-gray-900 dark:text-white mb-3"
                      >
                        适宜人群
                      </h4>
                      <div class="flex flex-wrap gap-2">
                        <el-tag
                          v-for="group in foodDetail.suitableGroups"
                          :key="group"
                          type="success"
                          effect="light"
                          class="mr-2"
                          >{{ group }}</el-tag
                        >
                      </div>
                    </div>
                  </div>
                  <div class="mt-4">
                    <h4 class="font-medium text-gray-900 dark:text-white mb-3">
                      温馨提示
                    </h4>
                    <ul
                      class="list-disc list-inside text-gray-600 dark:text-gray-400 space-y-2"
                    >
                      <li v-for="(tip, index) in foodDetail.tips" :key="index">
                        {{ tip }}
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar lg:w-80 flex-shrink-0">
          <!-- 特色标签 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6">
            <h3 class="text-lg font-bold mb-4">特色标签</h3>
            <div class="flex flex-wrap gap-2">
              <el-tag
                v-for="tag in foodDetail.tags"
                :key="tag"
                class="mr-2"
                effect="light"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>

          <!-- 美食地点 -->
          <div
            class="location-info bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6"
          >
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
              美食地点
            </h3>
            <p class="text-gray-600 dark:text-gray-400 mb-4">
              {{ foodDetail.location }}
            </p>
            <div ref="mapContainer" class="map-container h-48 rounded-lg overflow-hidden mb-4">
              <!-- 地图组件 -->
            </div>
            <div class="text-sm text-gray-600 dark:text-gray-400">
              <p class="flex items-center mb-2">
                <el-icon class="mr-2"><Location /></el-icon>
                <span>{{ foodDetail.location }}</span>
              </p>
            </div>
          </div>

          <!-- 相关推荐 -->
          <div
            class="related-food bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6"
          >
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2"><Connection /></el-icon>
              相关推荐
            </h3>
            <div class="related-food-list space-y-4">
              <div
                v-for="food in relatedFood"
                :key="food.id"
                class="related-food-item flex items-start gap-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 p-2 rounded-lg transition-all duration-300"
                @click="handleFoodClick(food)"
              >
                <el-image
                  :src="food.image"
                  class="w-20 h-20 rounded-lg object-cover flex-shrink-0"
                />
                <div class="flex-1 min-w-0">
                  <h4
                    class="text-sm font-medium text-gray-900 dark:text-white line-clamp-2 mb-1"
                  >
                    {{ food.name }}
                  </h4>
                  <div class="text-xs text-gray-500 dark:text-gray-400">
                    {{ food.category }}
                  </div>
                  <div
                    class="mt-1 flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400"
                  >
                    <span class="flex items-center">
                      <el-icon class="mr-1"><View /></el-icon>
                      {{ formatNumber(food.views, 'views') }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分享弹窗 -->
    <ShareDialog
      v-model="showShareDialog"
      :content="shareContent"
      @share="(type) => $emit('share', { type, content: shareContent })"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  Back,
  Location,
  View,
  Star,
  Share,
  ThumbsUp,
  Connection,
  CopyDocument,
  Wechat,
  Weibo,
  Food,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import ShareDialog from "@/components/global/ShareDialog.vue";
import service from "@/api/axios";

// 配置dayjs
dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const showShareDialog = ref(false);

// 测试用美食详情数据（备用）
const testFoodDetail = {
  id: 1,
  name: "贵港艇仔粥",
  category: "特色小吃",
  location: "贵港市港北区",
  views: 15680,
  likes: 2360,
  favorites: 890,
  isLiked: false,
  isFavorited: false,
  images: [
    "/images/food/food1-1.jpg",
    "/images/food/food1-2.jpg",
    "/images/food/food1-3.jpg",
  ],
  description: `
    <p>艇仔粥是贵港最具特色的传统美食之一，以其独特的烹饪方法和鲜美的口感而闻名。</p>
    <h3>特色介绍</h3>
    <p>艇仔粥选用上等大米，配以新鲜的河鲜食材，经过长时间熬制而成。粥质细腻，鲜味十足，是一道老少皆宜的美食。</p>
    <h3>制作工艺</h3>
    <p>传统的艇仔粥制作需要经过以下步骤：</p>
    <ul>
      <li>精选优质大米浸泡</li>
      <li>准备新鲜河鲜食材</li>
      <li>大火煮沸后改小火慢炖</li>
      <li>适时加入调味料</li>
    </ul>
  `,
  tags: ["传统美食", "早餐", "地方特色", "老字号"],
  restaurants: [
    {
      id: 1,
      name: "老字号艇仔粥店",
      image: "/images/restaurants/restaurant1.jpg",
      address: "贵港市港北区江北路123号",
      rating: 4.8,
      hours: "06:30-14:30",
    },
    {
      id: 2,
      name: "阿婆艇仔粥",
      image: "/images/restaurants/restaurant2.jpg",
      address: "贵港市港北区中山路45号",
      rating: 4.6,
      hours: "07:00-15:00",
    },
  ],
  tastes: [
    { name: "甜", description: "甜味十足，适合喜欢甜食的人" },
    { name: "咸", description: "咸味适中，适合喜欢咸味的人" },
  ],
  cookingSteps: [
    { title: "准备食材", description: "精选优质大米浸泡" },
    { title: "熬制粥底", description: "大火煮沸后改小火慢炖" },
    { title: "加入调味料", description: "适时加入调味料" },
  ],
  nutritions: [
    { value: "100", name: "热量" },
    { value: "20g", name: "蛋白质" },
    { value: "10g", name: "脂肪" },
    { value: "50g", name: "碳水化合物" },
  ],
  bestSeasons: ["春季", "秋季"],
  suitableGroups: ["儿童", "青少年", "成年人"],
  tips: ["趁热食用更美味", "搭配小菜更健康"],
};

// 测试用相关推荐（备用）
const testRelatedFood = [
  {
    id: 2,
    name: "荷叶粉",
    image: "/images/food/food2.jpg",
    category: "传统美食",
    views: 12460,
  },
  {
    id: 3,
    name: "贵港酿豆腐",
    image: "/images/food/food3.jpg",
    category: "地方特色",
    views: 10240,
  },
];

// 美食详情数据
const foodDetail = ref({});

// 相关推荐
const relatedFood = ref([]);

// 分享相关
const shareContent = computed(() => ({
  title: foodDetail.value.name,
  description: foodDetail.value.description,
  image: foodDetail.value.images?.[0] || '',
  url: window.location.href,
  views: foodDetail.value.views,
  likes: foodDetail.value.likes,
  shares: foodDetail.value.shares,
}));

// 格式化数字
const formatNumber = (num, type = 'views') => {
  // 如果数字不存在、为undefined、NaN或为0，生成随机模拟数据
  if (num === undefined || num === null || isNaN(num) || num === 0) {
    // 根据类型生成不同范围的随机数
    if (type === 'likes' || type === 'favorites') {
      return new Intl.NumberFormat().format(Math.floor(Math.random() * 2950) + 50);
    }
    // 对于浏览量，生成500-20000之间的随机数
    return new Intl.NumberFormat().format(Math.floor(Math.random() * 19500) + 500);
  }
  return new Intl.NumberFormat().format(num);
};

// 获取美食详情
const getFoodDetail = async () => {
  loading.value = true;
  const foodId = route.params.id;
  try {
    const response = await service.get(`/public/foods/${foodId}`);
    if (response && response.data) {
      // API返回的响应格式可能是 {code: 200, message: '成功', data: {...}} 
      // 或者直接是数据对象 {...}
      let foodData = response.data;
      if (response.code === 200 && response.data) {
        foodData = response.data;
      }
      
      // 确保有views和likes数据，如果不存在或为0则添加随机值
      if (foodData.views === undefined || foodData.views === null || isNaN(foodData.views) || foodData.views === 0) {
        foodData.views = Math.floor(Math.random() * 19500) + 500;
      }
      if (foodData.likes === undefined || foodData.likes === null || isNaN(foodData.likes) || foodData.likes === 0) {
        foodData.likes = Math.floor(Math.random() * 2950) + 50;
      }
      if (foodData.favorites === undefined || foodData.favorites === null || isNaN(foodData.favorites) || foodData.favorites === 0) {
        foodData.favorites = Math.floor(Math.random() * 1950) + 50;
      }
      
      // 检查并确保其他必要数据结构存在
      if (!foodData.images || !Array.isArray(foodData.images) || foodData.images.length === 0) {
        foodData.images = [
          foodData.cover || "/images/food/food1-1.jpg",
          "/images/food/food1-2.jpg",
          "/images/food/food1-3.jpg"
        ];
      }
      
      if (!foodData.tastes || !Array.isArray(foodData.tastes) || foodData.tastes.length === 0) {
        foodData.tastes = [
          { name: "香", description: "独特香气，回味悠长" },
          { name: "软", description: "口感柔软，细腻爽滑" }
        ];
      }
      
      if (!foodData.cookingSteps || !Array.isArray(foodData.cookingSteps) || foodData.cookingSteps.length === 0) {
        foodData.cookingSteps = [
          { title: "准备食材", description: "选用优质原料" },
          { title: "烹饪制作", description: "精心烹制而成" },
          { title: "装盘摆放", description: "精美摆盘，增添食欲" }
        ];
      }
      
      if (!foodData.nutritions || !Array.isArray(foodData.nutritions) || foodData.nutritions.length === 0) {
        foodData.nutritions = [
          { value: "100", name: "热量", unit: "kcal" },
          { value: "20", name: "蛋白质", unit: "g" },
          { value: "10", name: "脂肪", unit: "g" },
          { value: "50", name: "碳水化合物", unit: "g" }
        ];
      }
      
      if (!foodData.bestSeasons || !Array.isArray(foodData.bestSeasons) || foodData.bestSeasons.length === 0) {
        foodData.bestSeasons = ["春季", "秋季", "四季皆宜"];
      }
      
      if (!foodData.suitableGroups || !Array.isArray(foodData.suitableGroups) || foodData.suitableGroups.length === 0) {
        foodData.suitableGroups = ["儿童", "青少年", "成年人"];
      }
      
      if (!foodData.tips || !Array.isArray(foodData.tips) || foodData.tips.length === 0) {
        foodData.tips = ["趁热食用更美味", "搭配小菜更健康"];
      }
      
      if (!foodData.tags || !Array.isArray(foodData.tags) || foodData.tags.length === 0) {
        foodData.tags = [foodData.category || "传统美食", "美味佳肴", "特色小吃", "贵港特色"];
      }
      
      if (!foodData.restaurants || !Array.isArray(foodData.restaurants) || foodData.restaurants.length === 0) {
        foodData.restaurants = [
          {
            id: 1,
            name: `${foodData.name || '本地'}推荐餐厅`,
            image: "/images/restaurants/restaurant1.jpg",
            address: `贵港市${foodData.location || '市中心'}附近`,
            rating: 4.8,
            hours: "10:00-22:00"
          }
        ];
      }
      
      foodDetail.value = foodData;
      // 记录浏览量
      updateFoodViews(foodId);
    } else {
      // 使用测试数据作为备用
      foodDetail.value = testFoodDetail;
    }
  } catch (error) {
    console.error("获取美食详情失败:", error);
    // 使用测试数据作为备用
    foodDetail.value = testFoodDetail;
  } finally {
    loading.value = false;
  }
};

// 获取相关推荐
const getRelatedFood = async () => {
  const foodId = route.params.id;
  try {
    const response = await service.get(`/public/foods/related/${foodId}`);
    let relatedFoodData = [];
    
    // 检查响应格式
    if (response && response.data) {
      if (Array.isArray(response.data)) {
        relatedFoodData = response.data;
      } else if (response.code === 200 && Array.isArray(response.data)) {
        relatedFoodData = response.data;
      }
    }
    
    if (relatedFoodData.length > 0) {
      // 确保每个相关推荐项都有views数据，如果不存在或为0则添加随机值
      const processedData = relatedFoodData.map(item => {
        if (item.views === undefined || item.views === null || isNaN(item.views) || item.views === 0) {
          item.views = Math.floor(Math.random() * 19500) + 500;
        }
        // 确保有图片
        if (!item.image && item.cover) {
          item.image = item.cover;
        } else if (!item.image) {
          item.image = "/images/food/food3.jpg";
        }
        return item;
      });
      relatedFood.value = processedData;
    } else {
      // 使用测试数据作为备用
      relatedFood.value = testRelatedFood;
    }
  } catch (error) {
    console.error("获取相关推荐失败:", error);
    // 使用测试数据作为备用
    relatedFood.value = testRelatedFood;
  }
};

// 记录浏览量
const updateFoodViews = async (foodId) => {
  try {
    await service.post(`/public/foods/${foodId}/view`);
  } catch (error) {
    console.error("记录浏览量失败:", error);
    // 静默失败，不影响用户体验
  }
};

// 处理点赞
const handleLike = async () => {
  // 前端模拟点赞功能，无需调用API
  foodDetail.value.isLiked = !foodDetail.value.isLiked;
  foodDetail.value.likes += foodDetail.value.isLiked ? 1 : -1;
  ElMessage.success(foodDetail.value.isLiked ? "点赞成功" : "已取消点赞");
};

// 处理收藏
const handleFavorite = async () => {
  // 前端模拟收藏功能，无需调用API
  foodDetail.value.isFavorited = !foodDetail.value.isFavorited;
  foodDetail.value.favorites += foodDetail.value.isFavorited ? 1 : -1;
  ElMessage.success(foodDetail.value.isFavorited ? "收藏成功" : "已取消收藏");
};

// 处理分享
const handleShare = () => {
  showShareDialog.value = true;
};

// 处理美食点击
const handleFoodClick = (food) => {
  router.push(`/food/${food.id}`);
};

// 高德地图相关
const mapContainer = ref(null);
let map = null;
const mapKey = "ac63e78c8bfb172aac3c5be005a25f28"; // 高德地图Key
const securityJsCode = "bddeaa4d8587f8b446342a53ee0d4994"; // 高德地图安全密钥
const mapLoaded = ref(false);

// 设置高德地图安全密钥配置
if (typeof window !== 'undefined') {
  window._AMapSecurityConfig = {
    securityJsCode: securityJsCode
  };
}

// 加载高德地图脚本
const loadAMapScript = () => {
  return new Promise((resolve, reject) => {
    // 如果AMap已存在且可用，直接返回
    if (window.AMap && typeof window.AMap.Map === 'function') {
      resolve(window.AMap);
      return;
    }
    
    // 清除之前可能存在的脚本，防止冲突
    const existingScript = document.querySelector('script[src*="webapi.amap.com"]');
    if (existingScript) {
      existingScript.parentNode.removeChild(existingScript);
    }
    
    // 重置 AMap 对象，防止使用旧的实例
    if (window.AMap) {
      window.AMap = undefined;
    }
    
    // 确保安全配置已设置
    if (typeof window !== 'undefined' && !window._AMapSecurityConfig) {
      window._AMapSecurityConfig = {
        securityJsCode: securityJsCode
      };
    }
    
    // 添加时间戳防止缓存
    const timestamp = new Date().getTime();
    
    // 创建并加载脚本
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${mapKey}&plugin=AMap.PlaceSearch&t=${timestamp}`;
    
    script.onload = () => {
      resolve(window.AMap);
    };
    
    script.onerror = (error) => {
      reject(new Error('地图加载失败'));
    };
    
    document.head.appendChild(script);
  });
};

// 初始化地图
const initMap = async () => {
  try {
    // 确保地图容器存在
    if (!mapContainer.value || !document.body.contains(mapContainer.value)) {
      setTimeout(() => {
        initMap();
      }, 500);
      return;
    }

    // 确保地图尚未初始化
    if (map) return;

    // 加载高德地图脚本
    await loadAMapScript();

    // 再次确认DOM已经准备好
    if (!mapContainer.value || !document.body.contains(mapContainer.value)) {
      setTimeout(() => {
        initMap();
      }, 300);
      return;
    }

    // 创建地图实例，默认显示贵港市全貌
    map = new AMap.Map(mapContainer.value, {
      zoom: 14,
      center: [109.613196, 23.103333], // 贵港市中心坐标
      resizeEnable: true,
    });

    // 添加标记
    if (foodDetail.value.location) {
      searchFoodLocation(foodDetail.value.name, foodDetail.value.location);
    }
    
    mapLoaded.value = true;
  } catch (error) {
    console.error("地图初始化失败:", error);
  }
};

// 搜索美食地点位置并添加标记
const searchFoodLocation = (name, address) => {
  if (!map || !window.AMap) return;
  
  // 创建地点搜索实例
  const placeSearch = new AMap.PlaceSearch({
    pageSize: 1,
    pageIndex: 1,
    city: '贵港', // 限定城市
    citylimit: true,
  });

  // 优先使用完整地址搜索
  placeSearch.search(address, (status, result) => {
    if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
      // 获取第一个搜索结果的位置
      const position = [
        result.poiList.pois[0].location.lng,
        result.poiList.pois[0].location.lat
      ];
      
      // 添加标记
      addLocationMarker(position, name);
    } else {
      // 如果地址搜索失败，尝试使用美食名称搜索
      placeSearch.search(name, (status, result) => {
        if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
          const position = [
            result.poiList.pois[0].location.lng,
            result.poiList.pois[0].location.lat
          ];
          
          addLocationMarker(position, name);
        } else {
          console.warn("未找到美食地点位置");
        }
      });
    }
  });
};

// 添加地点标记
const addLocationMarker = (position, name) => {
  if (!map) return;
  
  // 清除之前的标记
  map.clearMap();
  
  // 创建标记
  const marker = new AMap.Marker({
    position: position,
    title: name,
    map: map,
    icon: new AMap.Icon({
      size: new AMap.Size(40, 40),
      image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
      imageSize: new AMap.Size(40, 40)
    }),
    offset: new AMap.Pixel(-20, -40)
  });
  
  // 设置地图中心和缩放级别
  map.setCenter(position);
  map.setZoom(15);
  
  // 创建信息窗体
  const infoWindow = new AMap.InfoWindow({
    content: `
      <div style="padding:10px;">
        <h3 style="font-weight:bold;margin-bottom:5px;">${name}</h3>
        <p style="font-size:12px;color:#666;">${foodDetail.value.location}</p>
      </div>
    `,
    offset: new AMap.Pixel(0, -30)
  });
  
  // 点击标记时显示信息窗口
  marker.on('click', () => {
    infoWindow.open(map, marker.getPosition());
  });
  
  // 自动打开信息窗口
  infoWindow.open(map, marker.getPosition());
};

// 清理地图资源
const cleanupMap = () => {
  try {
    // 销毁地图实例
    if (map) {
      map.clearMap();
      map.destroy();
      map = null;
    }
    
    mapLoaded.value = false;
  } catch (error) {
    console.warn("清理地图资源时发生错误:", error);
  }
};

// 页面加载时获取数据
onMounted(async () => {
  getFoodDetail();
  getRelatedFood();
  
  // 确保安全配置已设置
  if (typeof window !== 'undefined') {
    window._AMapSecurityConfig = {
      securityJsCode: securityJsCode
    };
  }
  
  // 确保DOM已更新
  await nextTick();
  
  // 延迟初始化，确保DOM完全渲染
  setTimeout(() => {
    initMap();
  }, 800);
});

onBeforeUnmount(() => {
  cleanupMap();
});
</script>

<style lang="scss" scoped>
.food-detail-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .food-description {
    @apply text-gray-700 dark:text-gray-300;

    :deep(h1) {
      @apply text-3xl font-bold text-gray-900 dark:text-white my-6;
    }

    :deep(h2) {
      @apply text-2xl font-bold text-gray-900 dark:text-white my-5;
    }

    :deep(h3) {
      @apply text-xl font-bold text-gray-900 dark:text-white my-4;
    }

    :deep(p) {
      @apply mb-4 leading-relaxed;
    }

    :deep(ul),
    :deep(ol) {
      @apply list-disc list-inside mb-4 space-y-2;
    }

    :deep(img) {
      @apply rounded-lg my-4 mx-auto;
    }

    :deep(blockquote) {
      @apply border-l-4 border-gray-200 dark:border-gray-700 pl-4 my-4 italic;
    }

    :deep(a) {
      @apply text-primary-600 dark:text-primary-400 hover:underline;
    }
  }

  :deep(.el-carousel__item) {
    .el-image {
      @apply dark:brightness-90;
    }
  }
}
</style>
